import { useMemo, createContext, useContext as useReactContext, useEffect } from 'react';
import Taro, { useDidShow } from '@tarojs/taro';
import { View, Image, Text } from '@tarojs/components';
import { getStatusBarHeight } from '../utils/ui';
import { getContrastYIQ } from '../utils/color';
import theme from '@/theme';
import TopView from '../TopView';

import back from './images/back.png';
import backWhite from './images/back-white.png';
import home from './images/home.png';
import homeWhite from './images/home-white.png';

import './index.scss';
import { getPlatform } from '@/utils/util';

const headerContext = createContext({});

const useContext = () => useReactContext(headerContext);
const homePagePath = '/pages/index/index';

const platform = getPlatform();

const HeaderBack = ({ show }) => {
  const option = useContext();

  const color = getContrastYIQ(option.color);

  return (
    (option.isBack || option.isBackHome || show) && (
      <View
        className='pd-header__nav__left'
        style={option.weapp ? { width: Taro.pxTransform(80) } : {}}
        onClick={() => {
          if (option.onBackClick) {
            option.onBackClick();
            return;
          }
          option.isBack ? Taro.navigateBack() : option.isBackHome ? Taro.reLaunch({ url: homePagePath }) : '';
        }}>
        {option.isBack && <Image src={color === 'black' ? backWhite : back} className='pd-header__nav__left__icon' />}
        {!option.isBack && option.isBackHome && <Image src={color === 'black' ? homeWhite : home} className='pd-header__nav__left__icon' />}
      </View>
    )
  );
};

const Header = ({
  color = theme.header.textColor, // 文字及返回按钮颜色 默认自动处理
  title, // 标题
  navTitle = title, // h5端页面标题
  absolute = false, // 是否使用绝对定位，不占位置
  show = true, // 是否显示配合absolute使用，直接使用则会直接出现
  style,
  renderMain = false, // 是否替换头部中间部分
  renderHeader, // 是否替换头部整个头部
  renderRight, // 右侧组件
  renderLeft,
  showStatus, // 使用了absolute的情况下时候显示status状态栏
  titleCenter, // 强制让title显示在中间 tabbar页面生效
  onBackClick, // 如果存在点击事件 则点击按钮时不会触发返回操作
}) => {
  /**
   * 收集当前页面配置
   */
  const { setConfig } = TopView.useContext();
  useMemo(() => {
    setConfig({
      title: navTitle,
    });
  }, [setConfig, navTitle]);

  useDidShow(() => {
    if (process.env.TARO_ENV === 'h5' && navTitle) {
      Taro.setNavigationBarTitle({ title: navTitle });
    }
  }, []);

  const option = useMemo(() => {
    Taro.getCurrentPages;
    const headerHeihgt = 44;
    // 小程序胶囊按钮宽度
    let jiaonangWidth = 0;
    // 获取胶囊信息
    if (process.env.TARO_ENV === 'weapp') {
      const { width } = Taro.getMenuButtonBoundingClientRect();
      jiaonangWidth = width + 10;
    }
    const statusBarHeight = getStatusBarHeight() || 0;

    const rn = process.env.TARO_ENV === 'rn';
    const h5 = process.env.TARO_ENV === 'h5';

    const weapp = !rn && !h5;

    // 是否显示header
    const showHeader =
      rn ||
      process.env.TARO_ENV === 'weapp' ||
      (platform === 'wechat' && theme.header.showWechat) ||
      (platform === 'wap' && theme.header.showWap) ||
      !!renderMain ||
      !!renderHeader;

    const bgColor = style?.backgroundColor || theme.header.color;

    const showHeight = headerHeihgt + (showStatus ? 0 : rn ? statusBarHeight : h5 ? 0 : statusBarHeight);

    const pages = Taro.getCurrentPages();
    const currentPagePath = Taro.getCurrentInstance().router.path;

    return {
      onBackClick,
      headerHeihgt,
      statusBarHeight,
      isBack: pages.length > 1,
      isBackHome: currentPagePath != homePagePath,
      jiaonangWidth,
      rn,
      h5,
      weapp,
      showHeader,
      bgColor,
      color,
      showHeight,
    };
  }, [color, onBackClick, renderHeader, renderMain, showStatus, style?.backgroundColor]);

  useEffect(() => {
    // 设置状态栏颜色
    setTimeout(() => {
      Taro.setNavigationBarColor({
        frontColor: getContrastYIQ(color) === 'white' ? '#000000' : '#ffffff',
        backgroundColor: 'transparent',
        animation: {
          duration: 400,
          timingFunc: 'easeIn',
        },
      });
    }, 100);
  }, [color]);

  const headerHeight = option.rn ? option.headerHeihgt : option.h5 ? Taro.pxTransform(88) : `${option.headerHeihgt}px`;

  return (
    <headerContext.Provider value={option}>
      {option.showHeader ? (
        <>
          {!show && showStatus && (
            <View
              style={{
                height: option.rn ? option.statusBarHeight : option.h5 ? 0 : `${option.statusBarHeight}px`,
                backgroundColor: option.bgColor,
              }}
            />
          )}
          {(show || absolute) && (
            <View className={`pd-header${absolute ? ' pd-header--absolute' : ''}`}>
              {(!absolute || option.rn) && (
                <View
                  style={{
                    height: option.rn ? option.showHeight : `${option.showHeight}px`,
                  }}
                />
              )}
              <View
                style={{
                  backgroundColor: option.bgColor,
                  ...style,
                }}
                className={`pd-header__main${show ? ' pd-header__main--show' : ''}`}>
                {option.rn ? (
                  <View style={{ height: option.statusBarHeight }} />
                ) : (
                  <View style={{ height: `${option.statusBarHeight}px` }} />
                )}
                {renderHeader ? (
                  <View style={{ paddingRight: option.jiaonangWidth, height: headerHeight }}>{renderHeader}</View>
                ) : (
                  <View className='pd-header__nav' style={{ height: headerHeight }}>
                    {renderLeft || <HeaderBack show={!!renderRight} />}
                    <View className='pd-header__nav__main'>
                      {renderMain || (
                        <Text
                          className='pd-header__nav__title'
                          numberOfLines={1}
                          style={{
                            color,
                            // 文本居中判断
                            textAlign: option.weapp && (option.isBack || !titleCenter) ? 'left' : 'center',
                            // 小程序没有返回按钮时，文本不要在最左边
                            paddingLeft: Taro.pxTransform(option.weapp && !option.isBack && !titleCenter ? 32 : 0),
                          }}>
                          {title}
                        </Text>
                      )}
                    </View>
                    {(option.isBack || option.isBackHome || !!renderRight) && (
                      <View
                        className='pd-header__nav__right'
                        style={
                          option.weapp
                            ? {
                                marginRight: option.jiaonangWidth + 'px',
                              }
                            : {}
                        }>
                        {renderRight}
                      </View>
                    )}
                  </View>
                )}
              </View>
            </View>
          )}
        </>
      ) : null}
    </headerContext.Provider>
  );
};

Header.Back = HeaderBack;
export default Header;
